var querystring = require("querystring"),
    fs = require("fs"),
    _ = require("underscore"),
    formidable = require("formidable");

function start(response) {
    console.log("Request handler 'start' was called.");

    var body = '<html>' +
        '<head>' +
        '<meta http-equiv="Content-Type" content="text/html; ' +
        'charset=UTF-8" />' +
        '</head>' +
        '<body>' +
        '<form action="/appword/mail/post_photo" enctype="multipart/form-data" ' +
        'method="post">' +
        '<input type="text" name="name"/>' +
        '<input type="text" name="psd"/>' +
        '<input type="file" name="upload" multiple="multiple">' +
        '<input type="submit" value="Upload file" />' +
        '</form>' +
        '</body>' +
        '</html>';

    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
    response.end();
}
var _path = "D:\\learnnodejs\\public\\image";
var _temp = _path + "\\test.png";
function upload(response, request) {
    console.log("Request handler 'upload' was called.");

    var form = new formidable.IncomingForm();
    form.uploadDir = _path;
    console.log("about to parse1");
    form.parse(request, function (error, fields, files) {
        console.log("parsing done");
        response.writeHead(200, {"Content-Type": "text/html"});
        var obj={};
        if(fields) {
            _.extend(obj,fields);
        }
        response.write("your fields:"+JSON.stringify(obj));
        if (files) {
            console.log(files.fulAvatar.path);
            fs.renameSync(files.fulAvatar.path, _temp);
            response.write("received image:<br/>");
            response.write("<img src='/show' />");
        }
        response.end();

    });
}

function show(response) {
    console.log("Request handler 'show' was called.");
    fs.readFile(_temp, "binary", function (error, file) {
        if (error) {
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(error + "\n");
            response.end();
        } else {
            response.writeHead(200, {"Content-Type": "image/png"});
            response.write(file, "binary");
            response.end();
        }
    });
}

exports.start = start;
exports.upload = upload;
exports.show = show;